package org.ring.csr.filter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.Utils;

public class StrictDuplicateCodeFilter extends AutomaticBean implements Filter {

	private Pattern pattern = null;
	private int min = 12;

	public StrictDuplicateCodeFilter() {
		setIgnoreLine("^$");
	}

	public boolean accept(AuditEvent aEvent) {
		boolean ret = true;
		if (aEvent.getSourceName().contains("StrictDuplicateCode")) {
			final String fileName = aEvent.getFileName();

			try {
				FileInputStream fis = new FileInputStream(fileName);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						fis));

				int lineNum = aEvent.getLine();
				int lines = parseLines(aEvent.getMessage());

				for (int i = 0; i < lineNum - 1; ++i) {
					br.readLine();
				}

				int lNum = 0;
				for (int i = 0; i < lines; ++i) {
					String line = br.readLine();
					if (!pattern.matcher(line).find()) {
						lNum++;
					}
				}

				if (lNum < min) {
					ret = false;
				}

				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public void setIgnoreLine(String patternStr) {
		this.pattern = Utils.getPattern(patternStr);
	}

	public void setMin(int value) {
		this.min = value;
	}

	private int parseLines(String msg) {
		StringTokenizer st = new StringTokenizer(msg);
		int i = 0;
		String token = null;
		while (st.hasMoreTokens() && i++ != 4) {
			token = st.nextToken();
		}

		int lines = Integer.parseInt(token);
		return lines;
	}
}
